<?php


namespace app\api\service;

use think\admin\Service;
use think\facade\Db;
use Yansongda\Pay\Pay;

/**
 * 订单管理
 * Class OrderService
 * @package app\api\service
 */
class OrderService extends Service
{

    /**
     * 生成订单
     * @param $order_data
     * @return array
     */
    public function createOrder($order_data): array
    {
        $now_time = date('Y-m-d H:i:s');
        $user_info = session('user');
        // 启动事务
        Db::startTrans();
        try {
            #计算收费金额
            $real_pay = $order_data['group_info']['group_price'] * $order_data['num'];
            $top_no = getOrderSn('top');
            #生成总订单
            sort($order_data['menu_ids']);
            $top_order_data = [
                'top_no' => $top_no,
                'user_id' => $user_info['id'],
                'group_id' => $order_data['group_info']['id'],
                'real_pay' => $real_pay,
                'num' => $order_data['num'],
                'menu_ids' => implode(',', $order_data['menu_ids']),
                'group_type' => 1, // 1：团长  2：团员
                'stu_name' => $order_data['stu_name'],
                'stu_mobile' => $order_data['stu_mobile'],
                'stu_type' => $order_data['stu_type'],
                'add_time' => $now_time
            ];
            $top_id = Db::table('pt_top_order')->insertGetId($top_order_data);
            if (!$top_id) throw new \Exception('总订单添加失败');
            // 提交事务
            Db::commit();
            $return_data = [
                'top_id' => $top_id,
                'top_no' => $top_no
            ];
            return ['status' => 1, 'info' => $return_data];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['status' => -1, 'info' => $e->getMessage()];
        }
    }

    public function doThirdPay($order_info, $data)
    {
        // 启动事务
        Db::startTrans();
        try {
            $now_time = date('Y-m-d H:i:s');
            $user_info = get_user_info(['id' => $order_info['user_id']]);
            $bool = Db::table('pt_top_order')->where(['top_id' => $order_info['top_id']])->save([
                'third_pay' => $data['total_amount'],
                'pay_status' => 1,
                'trade_no' => $data['trade_no'],
                'pay_time' => $now_time
            ]);
            if (!$bool) throw new \Exception('支付订单状态修改失败，请重试(001)~');
            // 提交事务
            Db::commit();
            return ['status' => 1, 'info' => '订单支付成功~'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['status' => -1, 'info' => $e->getMessage()];
        }
    }

    function doConfirmReturn($return_id, $money, $return_type = 1)
    {
        Db::startTrans();
        try {
            $now_time = date('Y-m-d H:i:s');
            $return_info = Db::table('pt_refund')->alias('a')
                ->field('a.*,b.pro_name,d.top_no,d.third_pay,d.return_money,d.real_pay')
                ->join('pt_son_order b', 'a.top_id=b.top_id')
                ->join('pt_top_order d', 'a.top_id=d.top_id')
                ->where(['refund_id' => $return_id])->findOrEmpty();
            if (empty($return_info)) throw new \Exception('未找到该退款订单~');
            //微信退款
            if ($money > $return_info['third_pay']) throw new \Exception("不可超额退款，最多退{$return_info['third_pay']}元");
            $user_info = get_user_info(1, ['a.id' => $return_info['user_id'], 'b.u_type' => 2]);
            //微信退款
            $return_no = getOrderSn('tui');
            $options = [
                'type' => 'miniapp',
                'out_trade_no' => $return_info['top_no'],              // 原商户订单号
                'out_refund_no' => $return_no,                         // 退款订单号
                'total_fee' => strval($return_info['real_pay'] * 100),       // 原订单交易总金额  金额分
                'refund_fee' => strval($money * 100),         // 申请退款金额   金额分
                'refund_desc' => '产品：' . $return_info['pro_name'] . ' 退款'
            ];
            $wx_pay_config = config('base.wx_pay_config');
            $result = Pay::wechat($wx_pay_config)->refund($options);
            if ($result['return_code'] == 'SUCCESS') {
                $bool = Db::table('pt_refund')->where(['refund_id' => $return_id])->save([
                    'refund_no' => $return_no,
                    'trade_no' => $result['refund_id'],
                    'update_time' => $now_time
                ]);
                if (!$bool) throw new \Exception('微信退款成功，订单状态修改失败（001）~');
                //改变订单状态
                $bool = Db::table('pt_top_order')->where(['top_id' => $return_info['top_id']])->save([
                    'pay_status' => $return_info['real_pay'] == $money ? 3 : 2,
                    'third_pay' => $return_info['third_pay'] - $money,
                    'return_type' => $return_type,
                    'return_id' => $return_info['refund_id'],
                    'return_money' => $return_info['return_money'] + $money,
                    'return_score' => $return_info['refund_score'],
                    'return_time' => $now_time
                ]);
                if (!$bool) throw new \Exception('微信退款成功，订单状态修改失败（002）~');
                $bool = Db::table('pt_son_order')->where(['top_id' => $return_info['top_id']])->save([
                    'order_status' => 6,
                    'update_time' => $now_time
                ]);
                if (!$bool) throw new \Exception('微信退款成功，订单状态修改失败（003）~');
                #返还安米
                if ($return_info['refund_score'] > 0) {
                    $bool = addUserScore($return_info['user_id'], $return_info['refund_score'], '订单退款返还积分', -1, $return_info['top_id'], $return_info['top_no'], 5);
                    if (!$bool) throw new \Exception('退款返还安米失败，请重试(004)~');
                }
                #退款订单
                $bool = Db::table('pt_refund')->where(['refund_id' => $return_id])->save(['status' => 2, 'update_time' => $now_time, 'refund_time' => $now_time, 'confirm_money' => $money]);
                if (!$bool) throw new \Exception('退款成功，退款订单状态修改失败，请重试(错误编码：005)~');
                #退款推送通知
                $mini_data = config('base.msg_template_list')['pt_fail'];
                $return_reason = !empty($return_info['reason']) ? $return_info['reason'] : config('base.reason_list')[$return_info['reason_index']]['name'];
                $mini_data['touser'] = $user_info['openid'];
                $mini_data['page'] = 'pages/order/orderDetails/orderDetails?id=' . $return_info['top_id'];
                $mini_data['data']['thing1'] = $return_info['pro_name'];
                $mini_data['data']['amount2'] = $return_info['real_pay'];
                $mini_data['data']['amount5'] = $money;
                $mini_data['data']['thing7'] = $return_reason;
                sendMiniMsg('app_group', $mini_data);
            } else {
                throw new \Exception($result);
            }
            Db::commit();
            return ['code' => 1, 'info' => '退款处理成功'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => -1, 'info' => $e->getMessage()];
        }
    }
}